package com.million.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.million.orderservice.entity.Order;
import com.million.orderservice.entity.PayLog;
import com.million.orderservice.mapper.PayLogMapper;
import com.million.orderservice.service.OrderService;
import com.million.orderservice.service.PayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.million.orderservice.utils.HttpClient;
import com.million.orderservice.utils.VxPayProperties;
import com.million.servicebase.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author 十麓
 * @since 2022-04-09
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    private OrderService orderService;

    //根据订单号 得到订单的信息
    @Override
    public PayLog getOrderLogInfo (String orderNo) {
        QueryWrapper<PayLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        return baseMapper.selectOne(queryWrapper);
    }

    //生成支付二维码 根据订单号
    @Override
    public Map<String, Object> createNative (String orderNo) {

        try {
            //根据订单号 获取订单信息
            Order orderInfo = orderService.getOrderInfo(orderNo);
            Map<String, String> m = new HashMap<>();

            //1、设置支付参数
            m.put("appid", VxPayProperties.APP_ID);
            m.put("mch_id", VxPayProperties.PARTNER); //商户号
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body", orderInfo.getCourseTitle());
            m.put("out_trade_no", orderNo);
            m.put("total_fee", orderInfo.getTotalFee().multiply(new
                    BigDecimal("100")).longValue() + "");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", VxPayProperties.NOTIFY_URL); //回调地址
            m.put("trade_type", "NATIVE");  //生成二维码的方式

            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            //后面的key 是商户key 根据它来对数据进行加密
            client.setXmlParam(WXPayUtil.generateSignedXml(m, VxPayProperties.PARTNER_KEY));
            client.setHttps(true);
            client.post();

            //3、返回第三方的数据 将xml 转换成map 集合
            String xml = client.getContent(); //因为前面将数据转换成了xml格式，返回的数据也是xml数据
            //这里保存了二维码的信息
            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(xml);
            //4、封装返回结果集 除了要二维码的信息外，还需要订单的其他信息，所有封装结果一并返回
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("out_trade_no", orderNo);
            resultMap.put("course_id", orderInfo.getCourseId());
            resultMap.put("total_fee", orderInfo.getTotalFee());
            resultMap.put("result_code", xmlToMap.get("result_code")); //生成的支付二维码的状态码
            resultMap.put("code_url", xmlToMap.get("code_url")); //二维码地址
            return resultMap;
        } catch (Exception e) {
            throw new GuliException(20001, "生成支付二维码失败");
        }
    }

    //根据订单号 查询订单支付状态 这里可以调用微信支付状态接口
    @Override
    public Map<String, String> queryPayStatus (String orderNo) {

        try {
            //1、封装参数
            Map<String, String> m = new HashMap<>();
            m.put("appid", VxPayProperties.APP_ID);
            m.put("mch_id", VxPayProperties.PARTNER);
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2.设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            //转换成xml  并用商户key 加密
            client.setXmlParam(WXPayUtil.generateSignedXml(m, VxPayProperties.PARTNER_KEY));
            client.setHttps(true); //设置https 请求
            client.post();

            //3.返回第三方的数据
            String xml = client.getContent();
            //转换成map 集合
            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(xml);
            //返回
            return xmlToMap;
        } catch (Exception e) {
            throw new GuliException(20001,"查询支付状态失败");
        }
    }

    //支付成功,添加到支付表中，并更新支付状态 将用微信支付状态接口返回的集合传入
    @Override
    public void updateOrderStatus (Map<String, String> map) {
        //1.得到订单号
        String orderNo = map.get("out_trade_no");
        //根据订单号得到订单信息
        Order orderInfo = orderService.getOrderInfo(orderNo);
        //判断订单状态是否支更新
        if(orderInfo.getStatus() == 1){
            return;
        }
        orderInfo.setStatus(1);
        orderService.updateById(orderInfo);
        //添加信息到支付表中
        //记录支付日志
        PayLog payLog=new PayLog();
        payLog.setOrderNo(orderInfo.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型
        payLog.setTotalFee(orderInfo.getTotalFee());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id")); //流水号
        payLog.setAttr(JSONObject.toJSONString(map)); //其他的信息
        baseMapper.insert(payLog); //插入到支付日志表
    }
}
